import api from "@/api";
import store from "@/store";
import { Message } from "element-ui";
import pinyin from "pinyin";

/** 
 * 获取子公司 
 * 会同步到vuex 调用vuex内容使用
 */
export const getCompanyList = async () => {
  // if (store.state.reward?.companyList?.length) return false;
  const { data } = await api.commonXc.initSubCompanyList().then((res) => res.data);
  store.dispatch("setCompanyList", data);
};

/** 
 * 获取职员
 * 会同步到vuex 调用vuex内容使用
 */
export const getEmployeeSalaryList = async () => {
  if (store.state.reward?.userList?.length) return false;
  
  const { data } = await api.commonXc.getEmployeeSalaryList({ companyId: store.state.common.userInfo.CompanyId }).then((res) => res.data);
  store.dispatch("setUserList", data.map((item) => {
    const { subId, companyid, userId, name, departmentid, departmentName, registertype } = item;
    return {
      subId,
      companyId: companyid,
      userId,
      userName: name,
      departmentId: departmentid,
      departmentName: departmentName,
      userType: registertype
    };
  }));
};

/**
 * 获取部门
 * @param {String} subid 子公司id
 * @param {Boolean} isEmply 是否清除子级空数组, 默认清除
 * @returns { data, status, message } 接口返回内容
 */
export const getDepartmentView = async (subid, isEmply = true) => {
  return await api.commonXc.getSalaryDepartmentTree({ subid }).then((res) => {
    if (isEmply) clearArray(res.data.data);
    return res.data;
  });
};


/** 清除空数组 */
function clearArray(arr = [], children = "childrenList") {
  arr.forEach((item) => {
    if (!item[children]?.length) item[children] = null;
    else clearArray(item[children]);
  });
}

/** 对比数组是否相同 */
export const diffArr = (now = [], old = []) => {
  console.log(now, old);
  if (now.length !== old.length) return 11;
  for (let i in now) {
    const bol = Array.isArray(now[i]) ? diffArr(now[i], old[i]) :
      typeof now[i] === 'object' ? diffObj(now[i], old[i]) :
        typeof now[i] === 'string' && !(now[i] == old[i]);
    if (bol > 0) return bol;
  }
  return false;
};

/** 对比对象是否相同 */
export const diffObj = (obj = {}, obj1 = {}, children = 'columnList') => {
  const key = Object.keys(obj);
  const key1 = Object.keys(obj1);
  if (key.length !== key1.length) return 13;
  for (let k of key) {
    // console.log(k, children, obj[k], obj1[k]);
    if (k == children) {
      const bol = diffArr(obj?.[children], obj1?.[children]);
      if (bol > 0) return bol;
    } else if (obj[k] !== obj1[k]) return 14;
  }
  return -2;
};

export const Base64 = {
  //加密
  encode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
      function toSolidBytes(match, p1) {
        return String.fromCharCode('0x' + p1);
      }));
  },
  //解密
  decode(str) {
    // Going backwards: from bytestream, to percent-encoding, to original string.
    return decodeURIComponent(atob(str).split('').map(function (c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
  }
};

/** 汉字转pinyin */
export const convertWord = (name) => {
  return pinyin(name, { style: 0 }).join("");
};

/**
 * 获取子公司 
 * 会同步到vuex 调用vuex内容使用
 * @returns 如果vuex中有值返回false
 */
export const getCityList = async () => {
  if (store.state.reward?.cityList?.length) return false;
  let { data } = await api.commonXc.GetAreaDataList().then((res) => res.data);
  // 将省市树中叶子节点的childList删掉
  data = JSON.parse(JSON.stringify(data).replace(/,"childList"\:\[\]/g, ''));
  store.dispatch("setCityList", data);
};

export const getBankList = async () => {
  if (store.state.reward?.bankList?.length) return false;
  const { data } = await api.commonXc.GetBankSelect().then((res) => res.data);
  store.dispatch("setBankList", data);
};

/** 错误信息拦截提示 */
export const errorMessage = message => {
  if (typeof message === "string" && message) Message({ message, type: "warning" });
};

/** 获取标准公式下拉内容 */
export const getStandardFormula = async() => {
  if(store.state.reward?.standardFormula?.length) return false;
  let { data } = await api.smartSalary.GetSystemFormulaTypeTemps().then(res=>res.data);
  store.dispatch("setStandardFormula", data);
};